from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_201_CREATED, HTTP_204_NO_CONTENT
from .models import *
from .serializers import *


# Create your views here  .
class StudentsViewSet(viewsets.ModelViewSet):
    queryset = Students.objects.filter(is_delete=False)
    serializer_class = StudentSerializer

    # def list(self, request):
    #     students = Students.objects.filter(is_delete=False)
    #     serializer = Studentserializer(students, many=True)
    #     return Response(serializer.data)
    #
    # def retrieve(self, request, pk):
    #     try:
    #         student = Students.objects.filter(is_delete=False).get(id=pk)
    #     except Students.DoesNotExist:
    #         return Response(HTTP_404_NOT_FOUND)
    #     serializer = Studentserializer(student)
    #     return Response(serializer.data)
    #
    # def create(self, request):
    #     serializer = Studentserializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     # 响应，返回创建成功序列化后的保存的学生信息
    #     return Response(serializer.data, status=HTTP_201_CREATED)
    #
    # def update(self, request, pk):
    #     try:
    #         student = Students.objects.filter(is_delete=False).get(id=pk)
    #     except Students.DoesNotExist:
    #         return Response(status=HTTP_404_NOT_FOUND)
    #     # serializer = Studentsserializer(data=student.data, instance=student)
    #     serializer = Studentsserializer(student, request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()  # 要求执行update方法
    #     return Response(serializer.data)
    #
    # def destroy(self, request, pk):
    #     try:
    #         student = Students.objects.filter(is_delete=False).get(id=pk)
    #     except Students.DoesNotExist:
    #         return Response(HTTP_404_NOT_FOUND)
    #     student.delete()
    #     return Response(HTTP_204_NO_CONTENT)


class ClassesViewSet(viewsets.ModelViewSet):
    """
    注释的内容会在接口文档显示
    list:
    返回所有的班级及其学生列表数据

    create:
    添加班级
    """
    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer

    @action(methods=['get'], detail=False)
    def last(self, request):
        classes = Classes.objects.last()
        return Response(self.get_serializer(classes).data)
